﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;

// you need to add these references to get this to work. :-)
using Microsoft.Xna.Framework.Audio;
using System.IO.IsolatedStorage;
using System.IO;

namespace GenetecHackathonCod3
{
    public partial class RecordingAudio : PhoneApplicationPage
    {

        // NOTE FOR SILVERLIGHT :   Because we are using XNA's Audio library, I had to add the code in the App.Xaml.CS
        //                          To allow the XNA engine to notify Silverlight that something interesting happened.

        public static Microphone microphone = Microphone.Default; // Microphone hardware instance
        private byte[] buffer;                              // Buffer To Hold Raw Audio Data
        private MemoryStream stream = new MemoryStream();   // Memory Stream to Pass Audio Data to Isolated Storage

        private DateTime date;

        bool recording = false;                            // Just a flag to see if we ar already recording
        bool error = true;
        // Constructor
        public RecordingAudio()
        {
            InitializeComponent();
            playBtn.IsEnabled = false;
            startBtn.IsEnabled = true;
            stopBtn.IsEnabled = false;
        }

        private void startBtn_Click(object sender, RoutedEventArgs e)
        {

            startBtn.IsEnabled = false;
            stopBtn.IsEnabled = true;

            // Don't start if we are already recording
            if (recording == false)
            {

                // We're recording 1/10th of a second buffers at a time
                microphone.BufferDuration = TimeSpan.FromMilliseconds(100);

                // Here we size our byte array to hold the audio
                buffer = new byte[microphone.GetSampleSizeInBytes(microphone.BufferDuration)];

                // This is our delegate handler for when the buffer get's full
                microphone.BufferReady += new EventHandler<EventArgs>(microphone_BufferReady);

                // yep... we're recording now!
                recording = true;
            }

            // Activate the Microphone
            microphone.Start();

        }


        // This is our delegate (event) handler for when the buffer get's full
        void microphone_BufferReady(object sender, EventArgs e)
        {

            // copy the microphone data into our buffer
            microphone.GetData(buffer);

            // tell the dispatcher to run this
            this.Dispatcher.BeginInvoke(() =>
            {
                // copy it to our stream (remember, we need the stream to pass to the audio player)
                stream.Write(buffer, 0, buffer.Length);
            }
        );

        }


        private void stopBtn_Click(object sender, RoutedEventArgs e)
        {

            stopBtn.IsEnabled = false;
            playBtn.IsEnabled = true;

            //ok user doesn't want to record anymore
            if (microphone.State == MicrophoneState.Started)
            {
                // so, if we were recording, we're not going to be after this line!
                microphone.Stop();

                // ok... no longer recording
                recording = false;
            }

            date = DateTime.UtcNow;

            // ok, here is where we store the file

            // first, we grab the current apps isolated storage handle
            IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();

            // we give our file a filename
            string strSaveName = "" + date.Second + date.Minute + date.Hour + date.Day + date.Month + date.Year + ".wav";

                
                // now we set up an isolated storage stream to point to store our data
                IsolatedStorageFileStream isfStream = new IsolatedStorageFileStream(strSaveName, FileMode.Create, IsolatedStorageFile.GetUserStoreForApplication());

                // tell it to actually write it out (remember, it's just raw data)
                isfStream.Write(stream.ToArray(), 0, stream.ToArray().Length);

                // ok, done with isolated storage... so close it
                isfStream.Close();

        }


        // magic method
        private void playBtn_Click(object sender, RoutedEventArgs e)
        {

            playSound("" + date.Second + date.Minute + date.Hour + date.Day + date.Month + date.Year + ".wav");

        }

        public static void playSound(String sound)
        {
            // again, grab the current apps isolated storage
            IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();

            // yep... we want to play the same file we recorded
            string strFileName = sound;

            // let's reverse what we did earlier... so we still need to get a file stream from isolated storage... but it's read mode
            IsolatedStorageFileStream isfStream = new IsolatedStorageFileStream(strFileName, FileMode.Open, IsolatedStorageFile.GetUserStoreForApplication());

            // remember, our data is raw, so we need to create a new buffer again to hold it (big enough to hold everything)
            byte[] b = new byte[isfStream.Length];

            // now we copy our file back in to our buffer
            isfStream.Read(b, 0, b.Length);

            // then we can pass it into our sound effect object... but tell it current samplerate and audio channels from the current hardware
            // NOTE: if you wanted to get adventerous and have a mechanism where you play these on a different machine, 
            // you'll also need to encode the samplerate and audiochannels in your file store and restore them as well
            // because those settings might be different for a different piece of hardware (phone)
            // luckily, since we're using the same hardware, the settings won't change
            SoundEffect se = new SoundEffect(b.ToArray(), microphone.SampleRate, AudioChannels.Mono);

            // lastly... a miracle occurs
            se.Play();

            //isfStream.Close();

        }


        private void SaveSound_Click(object sender, EventArgs e)
        {
            EditReport.currentReport.appendImage(new Image("" + date.Second + date.Minute + date.Hour + date.Day + date.Month + date.Year + ".wav"));
            NavigationService.Navigate(new Uri("/EditReport.xaml", UriKind.Relative));
            MainPage.save();
        }

    }
}